package it.amicosmanettone.finance.stocky;

import java.util.ArrayList;

import it.amicosmanettone.finance.stocky.adapter.ListAdapterStockPortfolio;
import it.amicosmanettone.finance.stocky.archive.ArchiveManager;
import it.amicosmanettone.finance.stocky.bean.SingleStockBean;
import it.amicosmanettone.finance.stocky.util.ErrorCode;
import it.amicosmanettone.finance.stocky.util.FinanceUtil;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;

public class StockPortfolioActivity extends SherlockActivity {

	static ListView listStocks = null;
	static ListAdapterStockPortfolio adapter = null;

	String nameOfPortfolio;
	String textTotalValueOfPortfolio;
	String currencyOfPortfolio;
	String textOfOkBox;
	String textError;
	
	ArrayList<SingleStockBean> list;
	
	int POSITION;
	int numStocks;

	double totalValueOfPortfolio;

	TextView textTotalValue;
	TextView textZeroStocks;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		getSupportActionBar().setIcon(R.drawable.default_image_portfolio);

		Bundle extras = getIntent().getExtras();

		this.nameOfPortfolio = extras.getString("nameOfPortfolio");
		this.POSITION = extras.getInt("POSITION");
		
		setContentView(R.layout.activity_stock_portfolio);
		
		Log.e("EXTRA", "Position: " + POSITION + ", " + nameOfPortfolio);

		
		this.list = FinanceUtil.getAllPortfolio().get(POSITION).getList();

		this.numStocks = list.size();
		
		Log.e("STOCKS", "STOCKS: " + numStocks);
		
		this.textZeroStocks = (TextView) findViewById(R.id.textZeroStocks);
		
		if (numStocks <= 0) {

			String noStocks = getText(R.string.portfolioRefreshNoStocks)
					.toString();
			this.textZeroStocks.setText(noStocks);

		} else if (numStocks > 0) {

			String yesStocksThird = getText(
					R.string.portfolioRefreshYesStocksThirst).toString();
			String yesStocksSecond = getText(
					R.string.portfolioRefreshYesStocksSecond).toString();
			Toast.makeText(this,
					yesStocksThird + " " + numStocks + " " + yesStocksSecond,
					Toast.LENGTH_SHORT).show();

		}
		
		Typeface monster = Typeface.createFromAsset(getAssets(), "monster.ttf");
		
		TextView textTitle = (TextView) findViewById(R.id.textTitleStockPortfolio);
		
		textTitle.setTypeface(monster);
		textTitle.refreshDrawableState();
		
		String numberOfStock = getText(R.string.stockPortfolioNumber).toString();

		this.listStocks = (ListView) findViewById(R.id.listStockPortfolio);
		registerForContextMenu(listStocks);

		this.adapter = new ListAdapterStockPortfolio(getApplicationContext(),
				R.layout.row_stock_portfolio, list, numberOfStock);

		listStocks.setAdapter(adapter);

		this.textTotalValueOfPortfolio = getText(R.string.totalValueOfPortfolio)
				.toString();
		this.totalValueOfPortfolio = FinanceUtil.getAllPortfolio().get(POSITION)
				.getTotalPortfolioValue();
		this.currencyOfPortfolio = FinanceUtil.getAllPortfolio().get(POSITION)
				.getCurrencyTotalPortfolioValue();

		setTitle(nameOfPortfolio);

		this.textTotalValue = (TextView) findViewById(R.id.textViewTotalPortfolioValue);

		textTotalValue.setText(textTotalValueOfPortfolio + "  "
				+ totalValueOfPortfolio + " " + currencyOfPortfolio);
		
		listStocks.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				initiatePopupWindow(position);
				
			}
		});

	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getSupportMenuInflater().inflate(R.menu.stock_portfolio, menu);
		if(FinanceUtil.IS_LITE_APP_VERSION == false){
			
			menu.removeItem(R.id.action_premium);
			
		}
		setupActionBar();
		getSupportActionBar();
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			NavUtils.navigateUpFromSameTask(this);
			return true;

		case R.id.action_addStock:

			Intent newStockIntent = new Intent(this, SearchStockActivity.class);
			newStockIntent.putExtra("nameOfPortfolio", this.nameOfPortfolio);
			newStockIntent.putExtra("POSITION", POSITION);
			startActivity(newStockIntent);

			return true;

		case R.id.action_refresh:

			boolean isUpdated = FinanceUtil
					.updateOnlyPortfolio(this.nameOfPortfolio);
			if (isUpdated) {

				String dialogText = getText(R.string.portfolioRefreshText)
						.toString();
				String toastNOStock = getText(R.string.portfolioRefreshNoStocks)
						.toString();
				String toastYESThirst = getText(
						R.string.portfolioRefreshYesStocksThirst).toString();
				String toastYESSecond = getText(
						R.string.portfolioRefreshYesStocksSecond).toString();
				
				String numberOfStock = getText(R.string.stockPortfolioNumber).toString();

				ProgressDialog mProgressDialog = new ProgressDialog(this);
				mProgressDialog.setMessage(dialogText);
				mProgressDialog.show();

				this.numStocks = FinanceUtil.getAllPortfolio().get(POSITION).getList().size();

				this.adapter = new ListAdapterStockPortfolio(getApplicationContext(),
						R.layout.row_stock_portfolio, FinanceUtil.getAllPortfolio().get(POSITION).getList(),numberOfStock);
				listStocks.setAdapter(adapter);

				Log.v("ACTIVITY", "RECUPERO " + numStocks + " STOCKS");

				mProgressDialog.dismiss();

				if (numStocks <= 0) {
					
					textZeroStocks.setText(toastNOStock);

				} else if (numStocks > 0) {

					Toast.makeText(this,
							toastYESThirst + " " + numStocks + " " + toastYESSecond,
							Toast.LENGTH_SHORT).show();
					
					textZeroStocks.setText("");

				}
			}

			return true;
			
		case R.id.action_premium:

			Toast.makeText(this, "PREMIUM", Toast.LENGTH_SHORT).show();

			return true;

		case R.id.action_settings:

			Intent settingsIntent = new Intent(this, SettingsActivity.class);
			startActivity(settingsIntent);

			return true;

		case R.id.action_information:
			
			Intent informationIntent = new Intent(this, InformationActivity.class);
			startActivity(informationIntent);

			return true;

		case R.id.action_reportBug:

			Intent reportBug = new Intent(this, MailActivity.class);
			reportBug.putExtra("nameOfActivity", "reportBug");
			startActivity(reportBug);

			return true;

		case R.id.action_advice:

			Intent reportAdvice = new Intent(this, MailActivity.class);
			reportAdvice.putExtra("nameOfActivity", "reportAdvice");
			startActivity(reportAdvice);

			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		
		String symbolOfStock = list.get(info.position).getStockSymbol();

		String modifyStock = getText(R.string.portfolioContextMenuModify)
				.toString();
		String deleteStock = getText(R.string.portfolioContextMenuDelete)
				.toString();

		menu.setHeaderTitle(symbolOfStock);
		menu.add(modifyStock);
		menu.add(deleteStock);

	}

	public boolean onContextItemSelected(android.view.MenuItem item) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

		String modifyStock = getText(R.string.portfolioContextMenuModify)
				.toString();
		String deleteStock = getText(R.string.portfolioContextMenuDelete)
				.toString();
		String error = getText(R.string.portfolioContextMenuError).toString();

		String nameOfStock = list.get(info.position).getStockName();

		if (item.getTitle().equals(deleteStock)) {

			deleteConfirm(nameOfStock, list.get(info.position));
			

		} else if (item.getTitle().equals(modifyStock)) {

			modifyValue(list.get(info.position));
			
		} else {

			Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
			return false;

		}

		return true;
	}
	
	public void okBox(String nameOfStock, String ACTION) {

		if (ACTION.equals("DELETE")) {

			this.textOfOkBox = getText(R.string.portfolioStockDelete).toString();

		}else if (ACTION.equals("NEW STOCK NUMBERS")) {

			this.textOfOkBox = getText(R.string.portfolioStockModifyOK).toString();

		}

		final String OKButton = getText(R.string.mainNewPortfolioOKButton)
				.toString();
		final String numberOfStock = getText(R.string.stockPortfolioNumber).toString();

		new AlertDialog.Builder(this)
				.setMessage(textOfOkBox + " " + nameOfStock)

				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								
								String toastNOStock = getText(R.string.portfolioRefreshNoStocks)
										.toString();
								
								adapter = new ListAdapterStockPortfolio(getApplicationContext(),
										R.layout.row_stock_portfolio, FinanceUtil.getAllPortfolio().get(POSITION).getList(), numberOfStock);
								listStocks.setAdapter(adapter);
								
								if (numStocks <= 0) {
									
									textZeroStocks.setText(toastNOStock);

								} else if (numStocks > 0) {
									
									textZeroStocks.setText("");

								}
								
								

							}
						}).show();

	}//End okBox
	
	public void deleteConfirm(final String nameOfStock, final SingleStockBean stockDeleted) {

		String title = getText(R.string.portfolioDeleteStockTitle).toString();
		String text = getText(R.string.portfolioDeleteStockText).toString();
		String buttonY = getText(R.string.portfolioDeleteStockYES).toString();
		String buttonN = getText(R.string.portfolioDeleteStockNO).toString();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title + " " + nameOfStock);
		alert.setMessage(text);
		alert.setCancelable(false);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				boolean DELETE = FinanceUtil.getAllPortfolio().get(POSITION).deleteStock(stockDeleted);
				
				if(DELETE == true){
					
					String STORE = ArchiveManager.storeAllPortfolios(getApplicationContext());
					
					if (STORE.equals(ErrorCode.NO_ERROR)) {
						okBox(nameOfStock,"DELETE");
						Log.v("SALVO PORT", "Mostro OK");
					} else {
						
						Log.v("SALVO PORT", "ERRORE");
					}
					
					
				}//End if delete == true

			}// End onClick
		});// End positiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of NegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}//End confirmDelete
	
	public void modifyValue(final SingleStockBean singleStockBean) {

		String title = getText(R.string.portfolioStockModifyTitle).toString();
		String text = getText(R.string.portfolioStockModifyText).toString();
		String buttonY = getText(R.string.portfolioStockModifyYES).toString();
		String buttonN = getText(R.string.portfolioStockModifyNO).toString();

		final String nameOfStock = singleStockBean.getStockName();
		long valueOfStock = singleStockBean.getStockNumbers();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title + " " + nameOfStock);
		alert.setMessage(text);
		alert.setCancelable(false);

		final EditText newNumbersOfStock = new EditText(this);
		newNumbersOfStock.setInputType(InputType.TYPE_CLASS_NUMBER);
		newNumbersOfStock.setText("" + valueOfStock);
		alert.setView(newNumbersOfStock);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String newNumbersOfStockText = newNumbersOfStock.getEditableText()
						.toString();

				if (newNumbersOfStockText.isEmpty()) {
					error("WRITE");
				} else if (!newNumbersOfStockText.isEmpty()) {

					long newNumbersOfStockInt = Integer.valueOf(newNumbersOfStockText);
					
					if(newNumbersOfStockInt >999999){
						
						error("LENGTH_STOCK");
						
					}
						
					
					singleStockBean.setStockNumbers(newNumbersOfStockInt);
					
					String STORE = ArchiveManager
							.storeAllPortfolios(getApplicationContext());
					
					if (STORE.equals(ErrorCode.NO_ERROR)) {
						Log.v("SALVO PORT", "Mostro OK");
						okBox(nameOfStock, "NEW STOCK NUMBERS");
					} else {
						Log.v("SALVO PORT", "ERRORE");
					}

				}

			} // End of onClick
		}); // End of alert.setPositiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of alert.setNegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}//End modifyValue
	
	public void error(String ACTION) {
		
		if(ACTION.equals("WRITE")){
			
			this.textError = getText(R.string.portfolioStockModifyErrorWrite).toString();
		}else if(ACTION.equals("LENGTH_ERROR")){
			
			this.textError = getText(R.string.addStockErrorNumLength).toString();
		}
		
		String OKButton = getText(R.string.mainNewPortfolioOKButton).toString();

		new AlertDialog.Builder(this)
				.setMessage(textError)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						}).show();

	}//End error

	private PopupWindow pwindo;

	@SuppressWarnings("deprecation")
	private void initiatePopupWindow(int position) {
		try {

			String stockCurrency = list.get(position).getStockCurrency();// Valuta originale di questa stock
			String stockMarket = list.get(position).getStockMarket();// Mercato di questa stock ad esempio NASDAQ
			String stockSymbol = list.get(position).getStockSymbol();// Stock symbol
			String stockName = list.get(position).getStockName();// Stock name
			double stockValue = list.get(position).getStockValue();// Valore singola azione...
			long stockNumbers = list.get(position).getStockNumbers();// Numero di azioni di questo tipo...
			double totalStockValue = list.get(position).getTotalStockValue();
			double stockTrend = list.get(position).getStockTrend();
			
			
			
			LayoutInflater inflater = (LayoutInflater) StockPortfolioActivity.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.stockportfolio_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			
			Button btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
			
			btnClosePopup.setOnClickListener(cancel_button_click_listener);
			
			TextView textNameStock = (TextView) layout.findViewById(R.id.textNameStock);
			
			
			TextView textCurrencyStock = (TextView) layout.findViewById(R.id.textCurrencyStock);
			String nameStockString = getText(R.string.popUpCurrencyStock).toString();
			
			TextView textValueStock = (TextView) layout.findViewById(R.id.textValueStock);
			String valueStockString = getText(R.string.popUpValueStock).toString();
			
			TextView textTotalValueStock = (TextView) layout.findViewById(R.id.textTotalValueStock);
			String totalValueStockString = getText(R.string.popUpTotalValueStock).toString();
			
			TextView textNumberStock = (TextView) layout.findViewById(R.id.textNumberStock);
			String numberStockString = getText(R.string.popUpNumberStock).toString();
			
			ImageView trendStock = (ImageView) layout.findViewById(R.id.trendStock);
			
			TextView textMarketStock = (TextView) layout.findViewById(R.id.textMarketStock);
			String marketStockString = getText(R.string.popUpMarketStock).toString();
			
			TextView textSymbolStock = (TextView) layout.findViewById(R.id.textSymbolStock);
			String symbolStockString = getText(R.string.popUpSymbolStock).toString();
			
			
			int WIDTH = 600;
			int HEIGHT = 900;
			pwindo = new PopupWindow(layout, WIDTH, HEIGHT, true);
			pwindo.setBackgroundDrawable(new BitmapDrawable());
			pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
			

			textNameStock.setText(stockName);
			textCurrencyStock.setText(nameStockString + " " + stockCurrency);
			textValueStock.setText(valueStockString + " " + stockValue);
			textTotalValueStock.setText(totalValueStockString + " " + totalStockValue);
			textNumberStock.setText(numberStockString + " " + stockNumbers);
			textMarketStock.setText(marketStockString + " " + stockMarket);
			textSymbolStock.setText(symbolStockString + " " + stockSymbol);
			if(stockTrend == 1){
				trendStock.setBackgroundResource(R.drawable.green_arrow);
			}else if(stockTrend == 0){
				trendStock.setBackgroundResource(R.drawable.equal);
			}else if(stockTrend < 0){
				trendStock.setBackgroundResource(R.drawable.red_arrow);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private OnClickListener cancel_button_click_listener = new OnClickListener() {
		public void onClick(View v) {
			pwindo.dismiss();

		}
	};

}
